package com.ruoyi.task;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;

import org.springframework.stereotype.Component;

import com.ruoyi.common.utils.http.HttpUtils;

@Component("sysTask")
public class SysTaskJob {
	
	/**
	 * 网络请求任务入口
	 * @param url 请求地址
	 * @throws Exception 
	 */
	public void http(String url) throws Exception{
		HttpUtils.sendGet(url, null);
	}

	/**
	 * 本地Shell任务入口
	 * @param shell 命令或者可执行文件
	 * @throws Exception 
	 */
	public void shell(String cmd) throws Exception{
		Runtime runtime = Runtime.getRuntime();
		Process pro = runtime.exec(cmd);
		int status = pro.waitFor();
		if (status != 0)
		{
			System.out.println("Failed to call command");
		}

		BufferedReader br = new BufferedReader(new InputStreamReader(pro.getInputStream()));
		StringBuffer strbr = new StringBuffer();
		String line;
		while ((line = br.readLine())!= null)
		{
			strbr.append(line).append("\n");
		}

		String result = strbr.toString();
		System.out.println(result);
	}
	
	/**
	 * 清理文件
	 * @param folder 目录
	 */
	public void clean(String folder){
		File f = new File(folder);
		if(!f.exists()) return;
		
		if(f.isFile()) {
			f.delete();
			return;
		}
		for(File s:f.listFiles()) {
			s.delete();
		}
	}

	/**
	 * 清理文件，指定保留的有效时长
	 * @param folder 目录
	 * @param dl 保留文件有效时长， 3s=3秒，3m=3分钟，4h=4小时，5d=5天，6M=6个月，7y=7年
	 */
	public void clean(String folder, String dl){
		File f = new File(folder);
		if(!f.exists()) return;
		
		long dt = System.currentTimeMillis();
		if(dl.endsWith("s")) {
			dt -= Long.parseLong(dl.substring(0, dl.length() - 1)) * 1000;
		}else if(dl.endsWith("m")) {
			dt -= Long.parseLong(dl.substring(0, dl.length() - 1)) * 60 * 1000;
		}else if(dl.endsWith("h")) {
			dt -= Long.parseLong(dl.substring(0, dl.length() - 1)) *  3600 * 1000;
		}else if(dl.endsWith("d")) {
			dt -= Long.parseLong(dl.substring(0, dl.length() - 1)) * 24 * 3600 * 1000;
		}else if(dl.endsWith("M")) {
			dt -= Long.parseLong(dl.substring(0, dl.length() - 1)) * 30 * 24 * 3600 * 1000;
		}else if(dl.endsWith("y")) {
			dt -= Long.parseLong(dl.substring(0, dl.length() - 1)) * 365 * 24 * 3600 * 1000;
		}else{ // d
			dt -= Long.parseLong(dl) * 24 * 3600 * 1000;
		}
		
		if(f.isFile()) {
			if(f.lastModified() < dt) f.delete();
			return;
		}
		for(File s:f.listFiles()) {
			if(s.lastModified() < dt) s.delete();
		}
	}
}
